<template>
  <a-card style="margin-top: 20px;margin-left: 16px;margin-right: 16px;">
    <a-tabs tab-position="left" default-active-key="1">
      <a-tab-pane key="1">
        <span slot="tab"
          ><a-icon type="profile" />
          基本信息
        </span>
        <!-- 基本信息内容 -->
        <a-page-header title="基本设置" />
        <a-card :bordered="false">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-model layout="vertical">
                <a-form-model-item label="用户名">
                  <a-input
                    v-model="userInfo.username"
                    placeholder="输入用户名"
                    disabled
                  />
                </a-form-model-item>
                <a-form-model-item label="邮箱">
                  <a-input v-model="userInfo.email" placeholder="输入邮箱" />
                </a-form-model-item>
                <a-form-model-item label="个人描述">
                  <a-input
                    v-model="userInfo.description"
                    placeholder="输入个人描述"
                  />
                </a-form-model-item>
                <a-form-model-item>
                  <a-button type="primary" @click="modifyUserInfo"
                    >修改信息</a-button
                  ></a-form-model-item
                >
              </a-form-model>
            </a-col>
            <a-col :span="12">
              <a-card :bordered="false">
                <a-form-model layout="vertical">
                  <a-form-model-item label="头像(单击更换头像)">
                    <a-upload
                      name="avatar"
                      list-type="picture-card"
                      class="avatar-uploader"
                      :headers="token"
                      :show-upload-list="false"
                      :action="URL + '/uploadAvatar'"
                      :before-upload="beforeUpload"
                      @change="handleChange"
                    >
                      <a-avatar
                        shape="square"
                        :size="128"
                        v-if="userInfo.avatar"
                        :src="userInfo.avatar"
                        alt="avatar"
                      />
                      <div v-else>
                        <a-icon :type="loading ? 'loading' : 'plus'" />
                        <div class="ant-upload-text">
                          Upload
                        </div>
                      </div>
                    </a-upload>
                  </a-form-model-item>
                </a-form-model>
              </a-card>
            </a-col>
          </a-row>
        </a-card>
        <!-- 基本信息内容 -->
      </a-tab-pane>
      <a-tab-pane key="2">
        <span slot="tab"
          ><a-icon type="safety-certificate" />
          安全设置
        </span>
        <a-page-header title="安全设置" />
        <a-list item-layout="horizontal" :data-source="data">
          <a-list-item slot="renderItem" slot-scope="item">
            <a-list-item-meta :description="item.description">
              <span slot="title">{{ item.title }}</span>
              <a-avatar
                :size="48"
                slot="avatar"
                :icon="item.icon"
                style="color:#fff;background: #1890ff;"
              />
            </a-list-item-meta>
            <a>修改</a>
          </a-list-item>
        </a-list>
      </a-tab-pane>
      <a-tab-pane v-if="role == 'student'" key="3">
        <span slot="tab"
          ><a-icon type="team" />
          账号绑定
        </span>
        <a-page-header title="账号绑定" />
        <a-card :bordered="false">
          <a-list item-layout="horizontal">
            <a-list-item v-for="item in classInfo" :key="item.id">
              <a-list-item-meta>
                <span slot="title" style="float:left;margin-top: 15px;"
                  >{{ item.className }}(ID:{{ item.classId }})</span
                >
                <a-avatar
                  :size="48"
                  style="color:#fff;background: #1890ff;"
                  slot="avatar"
                  icon="team"
                />
                <a
                  slot="description"
                  style="color:#ff4d4f;float:right;margin-top: 15px;"
                  >退出班级</a
                >
              </a-list-item-meta>
            </a-list-item>
            <a-list-item>
              <a-list-item-meta>
                <a slot="description" @click="showBindModal">添加班级</a>
              </a-list-item-meta>
            </a-list-item>
          </a-list>
        </a-card>
        <a-card :bordered="false">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-model layout="vertical">
                <a-form-model-item label="姓名">
                  <a-input placeholder="输入姓名" v-model="studentInfo.name" />
                </a-form-model-item>
                <a-form-model-item label="学号">
                  <a-input placeholder="输入学号" v-model="studentInfo.code" />
                </a-form-model-item>
                <a-form-model-item label="班级">
                  <a-input
                    placeholder="输入班级"
                    v-model="studentInfo.className"
                  />
                </a-form-model-item>
                <a-form-model-item label="学院">
                  <a-input
                    placeholder="输入学院"
                    v-model="studentInfo.college"
                  />
                </a-form-model-item>
                <a-form-model-item label="专业">
                  <a-input placeholder="输入专业" v-model="studentInfo.major" />
                </a-form-model-item>
                <a-form-model-item>
                  <a-button type="primary" @click="modifyStudentInfo"
                    >保存信息</a-button
                  ></a-form-model-item
                >
              </a-form-model></a-col
            >
            <a-col :span="16">
              <img
                src="https://img.smitish.com/wp-content/uploads/20200922202727.png"
                width="250px"
                alt=""
                style="border: 4px solid rgb(153, 153, 153);margin-top: 100px;margin-left: 50px;"
              />
            </a-col>
          </a-row>
        </a-card>
      </a-tab-pane>
    </a-tabs>
    <!-- 绑定班级的dialog -->
    <a-modal
      title="添加班级"
      :visible="bindVisible"
      :confirm-loading="confirmLoading"
      @cancel="bindHandleCancel"
      cancelText="取消"
      okText="确认"
      @ok="bindHandleOk"
    >
      <a-form-model-item label="邀请码">
        <a-input v-model="classId" placeholder="请输入老师所给的班级邀请码" />
      </a-form-model-item>
    </a-modal>
  </a-card>
</template>

<script>
import UpdateURL from "../../../axios.js";
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  data() {
    return {
      URL: "",
      userInfo: {
        username: "",
        email: "",
        description: "",
        avatar: "",
        id: ""
      },
      studentInfo: {
        id: "",
        className: "",
        code: "",
        college: "",
        major: "",
        name: ""
      },
      classInfo: [],
      token: {
        Authorization: localStorage.getItem("token")
      },
      loading: false,
      data: [
        {
          title: "账户密码",
          description: "当前密码强度:强",
          icon: "lock"
        },
        {
          title: "绑定邮箱",
          description: "",
          icon: "mail"
        }
      ],
      bindVisible: false,
      confirmLoading: false,
      classId: "",
      role:
        sessionStorage.getItem("cm9sZQ==") == "4eb118447d8e3cf0"
          ? "teacher"
          : "student"
    };
  },
  created() {
    this.URL = UpdateURL.posUrl;
    this.getUserInfo();
    this.getStudentInfo();
    this.getBindClassInfo();
  },
  methods: {
    getUserInfo() {
      this.$axios
        .get("/get/User/info", {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            // 获取完数据之后 给userInfo赋值
            this.userInfo.username = res.data.data.username;
            this.userInfo.email = res.data.data.email;
            this.userInfo.description = res.data.data.description;
            this.userInfo.avatar = res.data.data.avatar;
            this.userInfo.id = res.data.data.id;
            this.data[1].description = res.data.data.email;
            console.log(this.userInfo);
            // console.log(res.data.data);
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    getStudentInfo() {
      this.$axios
        .get("/get/student/owner/info", {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            // 获取完数据之后 给userInfo赋值
            this.studentInfo.className = res.data.data.className;
            this.studentInfo.code = res.data.data.code;
            this.studentInfo.college = res.data.data.college;
            this.studentInfo.major = res.data.data.major;
            this.studentInfo.name = res.data.data.name;
            this.studentInfo.id = res.data.data.id;
            // console.log(res.data.data);
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    getBindClassInfo() {
      this.$axios
        .get("/get/classes/join/info", {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.classInfo = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    handleChange(info) {
      if (info.file.status === "uploading") {
        return;
      }
      if (info.file.status === "done") {
        console.log(info);
        this.userInfo.avatar =
          info.fileList[info.fileList.length - 1].response.msg;
        // auto update database
        this.$axios
          .post(
            "/postAvatar",
            { avatar: this.userInfo.avatar },
            {
              headers: {
                Authorization: localStorage.getItem("token")
              }
            }
          )
          .then(res => {
            if (res.data.code == 200) {
              this.$message.success(res.data.msg);
            } else {
              this.$message.error(res.data.msg);
            }
          });
        console.log(this.userInfo.avatar);
        getBase64(info.file.originFileObj, imageUrl => {});
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    checkEmail() {
      var email = this.userInfo.email;
      var Reg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;

      if (Reg.test(email)) {
        return true;
      } else {
        return false;
      }
    },
    modifyUserInfo() {
      if (this.checkEmail()) {
        // 通过前端验证
        this.$axios
          .post("/modify/user/info", this.userInfo, {
            headers: {
              Authorization: localStorage.getItem("token")
            }
          })
          .then(res => {
            if (res.data.code == 200) {
              this.getUserInfo();
              this.$message.success(res.data.msg);
            } else {
              this.$message.error(res.data.msg);
            }
          });
      } else {
        this.$message.error("邮箱格式错误!");
      }
    },
    modifyStudentInfo() {
      this.$axios
        .post("/post/student/info", this.studentInfo, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.getStudentInfo();
            this.$message.success(res.data.msg);
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    showBindModal() {
      this.bindVisible = true;
    },
    bindHandleOk(e) {
      this.confirmLoading = true;
      // 开始提交绑定id表单
      this.$axios
        .get("/join/class/" + this.classId, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.getBindClassInfo();
            this.$message.success(res.data.msg);
          } else {
            this.$message.error(res.data.msg);
          }
        });
      setTimeout(() => {
        this.confirmLoading = false;
      }, 1000);
    },
    bindHandleCancel(e) {
      this.bindVisible = false;
    }
  }
};
</script>

<style>
.ant-tabs-tab-active {
  font-weight: 700;
  color: #1890ff;
  background-color: #e6f7ff;
}
.ant-page-header {
  padding-top: 0px;
}
.ant-list-item-meta-content1 {
  flex: 1 0;
  margin-top: 12px;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
